package com.css.economy.evaluate.controller;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.css.economy.evaluate.entity.EconomyModel;
import com.css.economy.evaluate.service.EconomyModelService;
import com.css.exception.CommonResult;
import com.css.exception.GlobalErrorCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author Dbj
 * @date 2024年09月23日  9:22
 * 经济损失模型
 */
@RestController
@Slf4j
@Validated
@RequestMapping("/economyModel")
public class EconomyModelController {

    @Resource
    EconomyModelService economyModelService;

    /**
     * 每个省只有一份经济损失的模型数据，且该模型数据默认内置在数据库中，
     * 所有没有新增操作，只有修改默认模型数据的操作
     */
    @PostMapping("/update")
    public CommonResult update(@Valid @RequestBody EconomyModel economyModel,HttpServletRequest request, BindingResult bindingResult){
        String code = request.getHeader("divisionCode");
        String divisionCode = code.split("_")[0];
        String userId = code.split("_")[1];
        economyModel.setUpdateUserId(userId);
        StringBuilder stringBuilder = new StringBuilder();
        while(bindingResult.hasFieldErrors()){
            stringBuilder.append("保存失败,");
            bindingResult.getFieldErrors().forEach(item->{
                String defaultMessage = item.getDefaultMessage();
                String field = item.getField();
                stringBuilder.append(field).append(defaultMessage).append(",");
            });
            if(!"保存失败,".contentEquals(stringBuilder)){
                //存在必填项为空的情况
                String msg = stringBuilder.substring(0,stringBuilder.lastIndexOf(","));
                return CommonResult.error(msg);
            }
        }
        try{
            // 切换到省份数据源
            DynamicDataSourceContextHolder.push("province_"+divisionCode);
            economyModelService.updateModelData(economyModel);
        }catch (Exception e){
            CommonResult error = CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode());
            error.setMsg("系统内部发生异常");
            e.printStackTrace();
            return error;
        }finally {
            DynamicDataSourceContextHolder.clear();
        }
        return CommonResult.success("保存成功");
    }


    /**
     * 获取经济损失模型数据
     */
    @GetMapping("/details")
    public CommonResult details(HttpServletRequest request){
        String code = request.getHeader("divisionCode");
        String divisionCode = code.split("_")[0];
        EconomyModel model = new  EconomyModel();
        try{
            // 切换到省份数据源
            DynamicDataSourceContextHolder.push("province_"+divisionCode);
            model = economyModelService.details();
        }catch (Exception e){
            CommonResult error = CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode());
            error.setMsg("系统内部发生异常");
            e.printStackTrace();
            return error;
        }finally {
            DynamicDataSourceContextHolder.clear();
        }
        return CommonResult.success(model);
    }
}
